package security.diffie.hellmann;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * Module de chiffrement.
 * @author Jean-François Augé
 */
// TODO implémenter un chiffrement plus sûr?
public class CipherModule {

	final static String DH_KEY_BEGIN = "---------- DH_KEY_BEGIN ----------";
	final static String DH_KEY_END = "---------- DH_KEY_END ----------";

	/**
	 * Chiffre en ECB.
	 * @param dh
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] chiffrement_ecb(DiffieHellman dh, byte[] in) throws IOException {
		byte[] out = new byte[in.length];
		byte[] key = dh.getK().toByteArray();
		
		for(int i=in.length-1;i>=0;i--)
			out[i] = (byte) (in[i] ^ key[i%dh.getKey_size()]);
		
		return out;
	}
	
	/**
	 * Chiffre en mode ECB.
	 * @param dh
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] chiffrement_ecb(String dh, byte[] in) throws IOException {
		byte[] out = new byte[in.length];
		byte[] key = dh.getBytes();
		
		for(int i=in.length-1;i>=0;i--)
			out[i] = (byte) (in[i] ^ key[i%dh.length()]);
		
		return out;
	}

	/**
	 * Ecrit une clé Diffie-Hellmann dans un fichier.
	 * @param fileName
	 * @param key
	 * @throws IOException
	 */
	public static void writeDHKey(String fileName, String key) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
		
		out.write(DH_KEY_BEGIN);
		out.newLine();
		out.write(key);
		out.newLine();
		out.write(DH_KEY_END);
		
        out.close();
	}

	/**
	 * Lit une clé Diffie-Hellmann dans un fichier.
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String readDHKey(String fileName) throws IOException {
		InputStream fis;
		BufferedReader br;
		String line;
		boolean isKeyNext = false;

		fis = new FileInputStream(fileName);
		br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
		while ((line = br.readLine()) != null) {
			if(isKeyNext) {
				br.close();
				return line;
			}
			if(line.equals(DH_KEY_BEGIN))
				isKeyNext = true;
		}

		br.close();
		return "";
	}

}
